package cn.iocoder.yudao.module.promotion.controller.app.yearcardorder;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.dict.core.util.DictFrameworkUtils;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.pay.api.notify.dto.PayOrderNotifyReqDTO;
import cn.iocoder.yudao.module.pay.api.order.PayOrderApi;
import cn.iocoder.yudao.module.pay.api.order.dto.PayOrderRespDTO;
import cn.iocoder.yudao.module.pay.enums.DictTypeConstants;
import cn.iocoder.yudao.module.promotion.controller.app.yearcardorder.vo.AppYearCardOrderCreateRespVO;
import cn.iocoder.yudao.module.promotion.controller.app.yearcardorder.vo.AppYearCardOrderPayRespVO;
import cn.iocoder.yudao.module.promotion.controller.app.yearcardorder.vo.AppYearCardOrderRespVO;
import cn.iocoder.yudao.module.promotion.dal.dataobject.yearcardorder.YearCardOrderDO;
import cn.iocoder.yudao.module.promotion.service.yearcardorder.YearCardOrderService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

@Tag(name = "用户 App - 年卡订单")
@RestController
@RequestMapping("/promotion/year-card-order")
@Validated
@Slf4j
public class AppYearCardOrderController {

    @Resource
    private YearCardOrderService yearCardOrderService;
    @Resource
    private PayOrderApi payOrderApi;

    @GetMapping("/get")
    @Operation(summary = "获得年卡订单")
    @PreAuthenticated
    public CommonResult<AppYearCardOrderRespVO> getYearCardOrder() {
        Long userId = getLoginUserId();
        YearCardOrderDO yearCardOrder = yearCardOrderService.getEnabledYearCardOrderByMemberId(userId);
        return success(yearCardOrder == null ? null : BeanUtils.toBean(yearCardOrder, AppYearCardOrderRespVO.class));
    }

    @GetMapping("/get-detail")
    @Operation(summary = "获得支付中的年卡订单")
    @Parameter(name = "id", description = "交易订单编号")
    @PreAuthenticated
    public CommonResult<AppYearCardOrderPayRespVO> getYearCardOrderDetail(@RequestParam Long id) {
        YearCardOrderDO yearCardOrder = yearCardOrderService.getYearCardOrder(id);
        if (yearCardOrder != null) {
            AppYearCardOrderPayRespVO result = new AppYearCardOrderPayRespVO();
            result.setNo(yearCardOrder.getOrderNo());
            result.setCreateTime(yearCardOrder.getCreateTime());
            result.setPayPrice(yearCardOrder.getYearCardAmount().multiply(new BigDecimal(100)).intValue());
            result.setPayStatus(Objects.equals(1, yearCardOrder.getPayOrderStatus()));
            PayOrderRespDTO payOrderRespDTO = payOrderApi.getOrder(yearCardOrder.getPayOrderId());
            if (StrUtil.isNotEmpty(payOrderRespDTO.getChannelCode())) {
                result.setPayChannelCode(payOrderRespDTO.getChannelCode());
                result.setPayChannelName(DictFrameworkUtils.getDictDataLabel(DictTypeConstants.CHANNEL_CODE, payOrderRespDTO.getChannelCode()));
                result.setStatus(payOrderRespDTO.getStatus());
            }
            return success(result);
        }
        return success(null);
    }

    @PostMapping("/create")
    @Operation(summary = "创建年卡订单")
    @PreAuthenticated
    public CommonResult<AppYearCardOrderCreateRespVO> createYearCardOrder() {
        Long userId = getLoginUserId();
        YearCardOrderDO order = yearCardOrderService.createOrder(userId, getClientIP());
        return success(new AppYearCardOrderCreateRespVO().setId(order.getId()).setPayOrderId(order.getPayOrderId()));
    }

    @PostMapping("/update-paid")
    @Operation(summary = "更新订单为已支付") // 由 pay-module 支付服务，进行回调，可见 PayNotifyJob
    public CommonResult<Boolean> updateOrderPaid(@RequestBody PayOrderNotifyReqDTO notifyReqDTO) {
        log.info("年卡订单支付回调, notifyReqDTO:{}", JSONUtil.toJsonStr(notifyReqDTO));
        yearCardOrderService.updateOrderPaid(Long.valueOf(notifyReqDTO.getMerchantOrderId()), notifyReqDTO.getPayOrderId());
        return success(true);
    }

}